#include "file_utils.h"
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <fstream>
#include <iostream>
#include <cstdio>
#include <sstream>

using namespace std;

void FileUtils::MDir(const char *dir)
{
    if (!dir)
    {
        return;
    }
    int len = 0;
    string *dirs = SplitPath(dir, len);
    if (len <= 0)
    {
        return;
    }
    for (int i = 0; i < len; i++)
    {
        stringstream ss;
        for (int j = 0; j <= i; j++)
        {
            ss << dirs[j] << "/";
        }
        DIR *pd = opendir(ss.str().c_str());
        if (!pd)
        {
            mkdir(ss.str().c_str(), 0775);
        }
    }
}

bool FileUtils::Exist(const char *dir)
{
    FILE *pf = fopen(dir, "r");
    if (!pf)
    {
        return false;
    }
    fclose(pf);
    return true;
}

void FileUtils::FWrite(const char *file_path, const char *txt, int len)
{
    string file_path_str(file_path);
    int pos = file_path_str.rfind("/");
    if (pos == string::npos)
    {
        return;
    }
    MDir(file_path_str.substr(0, pos + 1).c_str());
    FILE *pf = fopen(file_path, "w");
    if (!pf)
    {
        return;
    }
    fwrite(txt, 1, len, pf);
    fclose(pf);
}

string *FileUtils::SplitPath(const char *dir, int &size)
{
    string file_path_str(dir);
    int pos_start = 0;
    int pos_end = 0;
    size = 0;
    string *arr = new string[100];
    while ((pos_end = file_path_str.find("/", pos_start)) != string::npos)
    {
        string p = file_path_str.substr(pos_start, pos_end - pos_start);
        pos_start = pos_end + 1;
        if (p.empty())
        {
            continue;
        }
        arr[size++] = p;
    }
    string p = file_path_str.substr(pos_start);
    if (p.empty())
    {
        return arr;
    }
    arr[size++] = p;
    return arr;
}

string FileUtils::FRead(const char *path)
{
    FILE *pf = fopen(path, "r");
    if (!pf)
    {
        cout << path << " not exist..." << endl;
        return "";
    }
    fseek(pf, 0, SEEK_END);
    long pf_size = ftell(pf);
    char *buff = new char[pf_size];
    rewind(pf);
    int len = fread(buff, 1, pf_size, pf);

    if (len <= 0 || len != pf_size)
    {
        delete[] buff;
        fclose(pf);
        return "";
    }
    fclose(pf);
    string temp(buff, pf_size);
    delete[] buff;
    return temp;
}